package com.jwdf.uda.view.imagegetter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import com.jwdf.uda.app.AppContext;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;
import java.io.File;

/**
 * Created by Administrator on 2016/9/14.
 */
public class UiImageGetter implements Html.ImageGetter {

    private Context context;
    private EditText view;
    private int viewWillResetHeight;
    private CustomImageLoadingListener listener;
    private AppContext application;
    private static int screeWidth;

    public UiImageGetter(EditText view, Context context, AppContext application,int screeWidth) {

        this.application = application;
        this.context = context;
        this.view = view;
        this.screeWidth=screeWidth;
    }

    @Override
    public Drawable getDrawable(String source) {

        Log.d(Constants.tag, "UilImageGetter getDrawable is start PID = " + android.os.Process.myPid() + " Thread ID = " + Thread.currentThread().getId());
        URLDrawable urlDrawable = new URLDrawable(UiImageGetter.this.context);
        urlDrawable.setBounds(0, 0, urlDrawable.getIntrinsicWidth(), urlDrawable.getIntrinsicHeight());
        //实现方法一
//        listener = new CustomImageLoadingListener(urlDrawable);
//        ImageLoader.getInstance().loadImage(source,listener);

        //实现方法二
        // get the actual source
        ImageGetterAsyncTask asyncTask = new ImageGetterAsyncTask(urlDrawable);
        asyncTask.execute(source);

//        Bitmap bitmap = ImageLoader.getInstance().loadImageSync(source);
//        UiImageGetter.this.replaceImage(bitmap,urlDrawable);

        return urlDrawable;
    }

    public class ImageGetterAsyncTask extends AsyncTask<String, Void, Bitmap> {

        URLDrawable urlDrawable;

        public ImageGetterAsyncTask(URLDrawable urlDrawable) {
            this.urlDrawable = urlDrawable;
        }

        @Override
        protected Bitmap doInBackground(String... params) {

            String source = params[0];
            Bitmap bitmap = ImageLoader.getInstance().loadImageSync(source);
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) {

            UiImageGetter.this.replaceImage(result,urlDrawable);
        }
    }

    private class CustomImageLoadingListener extends SimpleImageLoadingListener {

        private URLDrawable urlDrawable;

        CustomImageLoadingListener(URLDrawable urlDrawable){

            this.urlDrawable = urlDrawable;
        }

        @Override
        public void onLoadingStarted(String imageUri, View view) {

            super.onLoadingStarted(imageUri,view);
            File discCacheImg = DiskCacheUtils.findInCache(imageUri,UiImageGetter.this.application.discCache);
            Log.d(Constants.tag, "CustomImageLoadingListener onLoadingStarted is run discCacheImg = " + discCacheImg);
        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

            //TODO:
            //do something
            super.onLoadingFailed(imageUri,view,failReason);
            Log.d(Constants.tag, "CustomImageLoadingListener onLoadingFailed is run imageUri = " + imageUri);
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

            super.onLoadingComplete(imageUri, view, loadedImage);
            UiImageGetter.this.replaceImage(loadedImage,this.urlDrawable);
            File discCacheDir = UiImageGetter.this.application.discCache.getDirectory();
            Log.d(Constants.tag, "CustomImageLoadingListener onLoadingComplete is run discCacheDir = " + discCacheDir);
            File discCacheImg = UiImageGetter.this.application.discCache.get(imageUri);
            Log.d(Constants.tag, "CustomImageLoadingListener onLoadingComplete is run discCacheImg = " + discCacheImg);
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {

            super.onLoadingCancelled(imageUri,view);
            //TODO:
            //do something
        }
    }

    public void replaceImage(final Bitmap loadedImage,final URLDrawable urlDrawable) {
        this.view.post(new Runnable() {
            @Override
            public void run() {
                if (null != loadedImage) {

                    //按照240dip,对px和dp做处理
                   final int loadedImageWidth = (int) Math.round(loadedImage.getWidth()/2);
                    final int loadedImageheight = (int) Math.round(loadedImage.getHeight()/2);
                    ViewTreeObserver vto = UiImageGetter.this.view.getViewTreeObserver();
//                    UiImageGetter.this.view.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            screeWidth=UiImageGetter.this.view.getWidth();
//                            float proportion=(float) screeWidth/loadedImageWidth;
//                            float floatHeight=(float)proportion*loadedImageheight;
//                            int intHeight=(int)(floatHeight+0.5f);
//                            Log.i("---2313----","screWidth"+screeWidth+"-----"+intHeight);
//                            Drawable result = new BitmapDrawable(context.getResources(), loadedImage);
//                            result.setBounds(0, 0, screeWidth, intHeight);
//                            urlDrawable.setBounds(0, 0, screeWidth, intHeight);
//                            urlDrawable.drawable  = result;
//
//                            if(0 != UiImageGetter.this.viewWillResetHeight) {
//
//                                UiImageGetter.this.viewWillResetHeight += intHeight;
//
//                            }else {
//
//                                UiImageGetter.this.viewWillResetHeight = UiImageGetter.this.view.getHeight() + intHeight;
//                            }
//
//                            //http://stackoverflow.com/questions/7870312/android-imagegetter-images-overlapping-text
//                            // For ICS
//                            UiImageGetter.this.view.setHeight(UiImageGetter.this.viewWillResetHeight);
//
//                            // Pre ICS
//                            UiImageGetter.this.view.setEllipsize(null);
//                            UiImageGetter.this.view.invalidate();
//                        }
//                    });
                    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                        public boolean onPreDraw() {
                            screeWidth =  UiImageGetter.this.view.getMeasuredWidth();
                            float proportion=(float) screeWidth/loadedImageWidth;
                            float floatHeight=(float)proportion*loadedImageheight;
                            int intHeight=(int)(floatHeight+0.5f);
                            Log.i("---2313----","screWidth"+screeWidth+"-----"+intHeight);
                            Drawable result = new BitmapDrawable(context.getResources(), loadedImage);
                            result.setBounds(0, 0, screeWidth, intHeight);
                            urlDrawable.setBounds(0, 0, screeWidth, intHeight);
                            urlDrawable.drawable  = result;

                            if(0 != UiImageGetter.this.viewWillResetHeight) {

                                UiImageGetter.this.viewWillResetHeight += intHeight;

                            }else {

                                UiImageGetter.this.viewWillResetHeight = UiImageGetter.this.view.getHeight() + intHeight;
                            }

                            //http://stackoverflow.com/questions/7870312/android-imagegetter-images-overlapping-text
                            // For ICS
                            UiImageGetter.this.view.setHeight(UiImageGetter.this.viewWillResetHeight);

                            // Pre ICS
                            UiImageGetter.this.view.setEllipsize(null);
                            UiImageGetter.this.view.invalidate();
                            return true;
                        }
                    });

//                    Editable eb = UiImageGetter.this.view.getEditableText();
//                    int startPosition = UiImageGetter.this.view.getSelectionStart();
//                    eb.insert(startPosition, "");
                }
            }
        } );
    }
}
